package com.lin.lazybone.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lin.lazybone.R;
import com.lin.lazybone.adapter.ChatListAdapter;
import com.lin.lazybone.application.BaseActivity;
import com.lin.lazybone.entity.ChatBean;
import com.lin.lazybone.entity.Message;
import com.lin.lazybone.entity.Order;
import com.lin.lazybone.entity._User;
import com.lin.lazybone.fragment.MesFragment;
import com.lin.lazybone.utils.L;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.bean.BmobIMMessage;
import cn.bmob.newim.bean.BmobIMTextMessage;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.newim.core.BmobIMClient;
import cn.bmob.newim.core.ConnectionStatus;
import cn.bmob.newim.event.MessageEvent;
import cn.bmob.newim.listener.ConversationListener;
import cn.bmob.newim.listener.MessageListHandler;
import cn.bmob.newim.listener.MessageSendListener;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;

/**
 * Created by mr.lin on 2017/11/23.
 */

public class ChatActivity extends BaseActivity implements View.OnClickListener, MessageListHandler
{
    private TextView chat_name;
    //    private ImageView chat_orderImage;
//    private TextView chat_orderPrice;
//    private TextView chat_orderType;
//    private TextView chat_orderAddress;
    private ListView chatList;
    private EditText chat_mesEdit;
    private Button chat_sendButton;
    private Order order;
    //    private Map<String, Integer> mDelTypeMap;
    public static List<ChatBean> mList;
    public static ChatListAdapter adapter;
    private _User thridUser;
    private BmobIMUserInfo info;
    private Intent intent;
    private BmobIMConversation mConversationManager;
    //判断是从哪里来到本活动的，0表示从发布者自己的需求列表进来，1表示从抢单者的任务中进来,2表示从消息列表进来
    private int temp;
    private String youname;


    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        Toolbar toolbar = (Toolbar) findViewById(R.id.getdel_toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null)
        {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        intent = getIntent();
//        order = (Order) intent.getSerializableExtra("order_data");

        temp = intent.getIntExtra("FromWhere", -1);
        initData();
        initView();

        temp = intent.getIntExtra("FromWhere", -1);
        youname = intent.getStringExtra("name");
        chat_name.setText(youname);
        getUserFromServe();
        //0表示从发布者自己的需求列表进来，1表示从抢单者的任务中进来,2表示从消息列表进来
//        if (temp == 1)
//        {
////            chat_name.setText(order.getOrder_aid());
//            updateViews();
//        } else if (temp == 0)
//        {
////            chat_name.setText(order.getOrder_uid());
//            updateViews();
//        } else if (temp == 2)
//        {
////            String orderid = intent.getStringExtra("orderId");
//            chat_name.setText(intent.getStringExtra("name"));
////            if (orderid != null)
////            {
////                //从服务器获取到对应order
////                getorderFromServe(orderid);
////            }
//        }


    }

    //从服务器上获取订单消息
//    private void getorderFromServe(final String orderid)
//    {
//        new Thread(new Runnable()
//        {
//            @Override
//            public void run()
//            {
//                //通过orderid查询单条order
//                BmobQuery<Order> query = new BmobQuery<Order>();
//                query.getObject(orderid, new QueryListener<Order>()
//                {
//                    @Override
//                    public void done(Order object, BmobException e)
//                    {
//                        if (e == null)
//                        {
//                            order = object;
//                            runOnUiThread(new Runnable()
//                            {
//                                @Override
//                                public void run()
//                                {
//                                    Toast.makeText(ChatActivity.this, "获取order成功", Toast.LENGTH_SHORT).show();
//                                    updateViews();
//                                }
//                            });
//                        } else
//                        {
//                            Toast.makeText(ChatActivity.this, "获取Order失败", Toast.LENGTH_SHORT).show();
//                        }
//                    }
//
//                });
//            }
//        }).start();
//    }

    //更新ui
//    private void updateViews()
//    {
////        chat_orderImage.setImageResource(mDelTypeMap.get(order.getOrder_del_type()));
////        chat_orderPrice.setText("￥ " + order.getOrder_price());
////        chat_orderType.setText(order.getOrder_type() ? "取快递" : "寄快递");
////        chat_orderAddress.setText(order.getOrder_from() + "-->" + order.getOrder_to());
//        getUserFromServe();
//    }

    //获取对方user
    private void getUserFromServe()
    {
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                BmobQuery<_User> query = new BmobQuery<_User>();
                query.addWhereEqualTo("username", youname);
                query.findObjects(new FindListener<_User>()
                {
                    @Override
                    public void done(List<_User> list, BmobException e)
                    {
                        if (e == null)
                        {
                            thridUser = list.get(0);
                            runOnUiThread(new Runnable()
                            {
                                @Override
                                public void run()
                                {
                                    bmobIMInit();
                                }
                            });
                            L.i("查询用户信息成功");
                        } else
                        {
                            L.i("查询用户信息失败" + e.getMessage());
                        }
                    }
                });
            }
        }).start();
    }

    private void bmobIMInit()
    {
        info = new BmobIMUserInfo();
        info.setName("name");
        info.setUserId(thridUser.getUsername());
        info.setAvatar("touxiang");
        //TODO 会话：4.1、创建一个常态会话入口，陌生人聊天
        BmobIM.getInstance().startPrivateConversation(info, new ConversationListener()
        {
            @Override
            public void done(BmobIMConversation bmobIMConversation, BmobException e)
            {
                if (e == null)
                {
                    mConversationManager = BmobIMConversation.obtain(BmobIMClient.getInstance(), bmobIMConversation);
                }
            }
        });

    }


    private void initView()
    {
        chat_name = (TextView) findViewById(R.id.chat_name);
//        chat_orderImage = (ImageView) findViewById(R.id.chat_orderImage);
//        chat_orderPrice = (TextView) findViewById(R.id.chat_orderPrice);
//        chat_orderType = (TextView) findViewById(R.id.chat_orderType);
//        chat_orderAddress = (TextView) findViewById(R.id.chat_orderAddress);
        chatList = (ListView) findViewById(R.id.chatList);
        adapter = new ChatListAdapter(this, mList);
        chatList.setAdapter(adapter);
        chat_mesEdit = (EditText) findViewById(R.id.chat_mesEdit);
        chat_sendButton = (Button) findViewById(R.id.chat_sendButton);
        chat_sendButton.setOnClickListener(this);
    }

    private void initData()
    {
        //初始化快递信息
//        mDelTypeMap = new HashMap<>();
//        mDelTypeMap.put("顺丰", R.drawable.sf_mini);
//        mDelTypeMap.put("申通", R.drawable.sto_mini);
//        mDelTypeMap.put("中通", R.drawable.zto_mini);
//        mDelTypeMap.put("ems", R.drawable.ems_mini);
//        mDelTypeMap.put("百世汇通", R.drawable.best_mini);
//        mDelTypeMap.put("圆通", R.drawable.yt_mini);
//        mDelTypeMap.put("韵达", R.drawable.yunda_mini);
        mList = new ArrayList<>();
//        mList.add(new ChatBean(1, "你好", R.drawable.touxiang));
//        mList.add(new ChatBean(0, "你好", R.drawable.touxiang));
//        mList.add(new ChatBean(1, "你好", R.drawable.touxiang));
//        mList.add(new ChatBean(0, "你好", R.drawable.touxiang));
        if (temp == 2)
        {
            String recentmes = intent.getStringExtra("recentmes");
            if (recentmes != null)
            {
                mList.add(new ChatBean(0, recentmes, R.drawable.touxiang));
            }
        }
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        //如果聊天记录不为空，把本条联系消息加到主页面消息列表
        if (!mList.isEmpty())
        {
            upMessage();
        }
    }

    private void upMessage()
    {
        //上传到服务器上
        _User user = BmobUser.getCurrentUser(_User.class);
        final Message message = new Message();
//        message.setOrderId(order.getObjectId());
        message.setMyname(user.getUsername());
        //0表示从发布者自己的需求列表进来，1表示从抢单者的任务中进来,2表示从消息列表进来
        message.setYourname(youname);
        message.setTouxiang(R.drawable.touxiang);
//        message.setDelImageId(mDelTypeMap.get(order.getOrder_del_type()));
        message.setRecentMes(mList.get(mList.size() - 1).getContent());
        L.i(mList.get(mList.size() - 1).getContent());
        message.setTime("1天前");
        message.save(new SaveListener<String>()
        {
            @Override
            public void done(String s, BmobException e)
            {
                Toast.makeText(ChatActivity.this, "上传新聊天成功", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.chat_sendButton:
                //点击了发送按钮
                String content = chat_mesEdit.getText().toString();
                if (!TextUtils.isEmpty(content.trim()))
                {
                    sendMessage(content);

                } else
                {
                    Toast.makeText(this, "不能发送空消息", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    /**
     * 发送文本消息
     */
    private void sendMessage(final String content)
    {
        //TODO 发送消息：6.1、发送文本消息
        BmobIMTextMessage msg = new BmobIMTextMessage();
        msg.setContent(content);
        mConversationManager.sendMessage(msg, new MessageSendListener()
        {
            @Override
            public void done(BmobIMMessage bmobIMMessage, BmobException e)
            {
                if (e == null)
                {
                    L.i("发送成功");
                    runOnUiThread(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            mList.add(new ChatBean(1, content, R.drawable.touxiang));
                            adapter.notifyDataSetChanged();
                            chatList.smoothScrollToPosition(mList.size());
                            chat_mesEdit.setText("");
                        }
                    });
                }
            }
        });
    }

    //TODO 消息接收：8.2、单个页面的自定义接收器
    @Override
    public void onMessageReceive(List<MessageEvent> list)
    {
        MessageEvent m = list.get(0);
        L.i("youname=" + youname + "getname= " + m.getFromUserInfo().getUserId());

        if (youname.equals(m.getFromUserInfo().getUserId()))
        {
            mList.add(new ChatBean(0, m.getMessage().getContent(), R.drawable.touxiang));
            adapter.notifyDataSetChanged();
            chatList.smoothScrollToPosition(mList.size());
        }

    }

    @Override
    protected void onResume()
    {
        super.onResume();
        //添加页面消息监听器
        BmobIM.getInstance().addMessageListHandler(this);
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        //移除页面消息监听器
        BmobIM.getInstance().removeMessageListHandler(this);
    }
}